package com.tticar.invmanager.controller;

import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.tticar.invmanager.common.utils.MoneyTransformUtil;
import com.tticar.invmanager.common.utils.MyResponseBody;
import com.tticar.invmanager.common.utils.date.DateStyle;
import com.tticar.invmanager.common.utils.date.DateUtil;
import com.tticar.invmanager.entity.*;
import com.tticar.invmanager.entity.vo.*;
import com.tticar.invmanager.mapper.OutRepositoryDetailMapper;
import com.tticar.invmanager.service.*;
import com.tticar.invmanager.tticar.mapper.GoodsOrderMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.*;

/**
 * <p>
 * 出库单详情 前端控制器
 * </p>
 *
 * @author joeyYan
 * @since 2018-08-06
 */
@Controller
@RequestMapping("/outRepositoryDetail")
public class OutRepositoryDetailController extends BaseController {

    @Autowired
    private IOutRepositoryDetailService outRepositoryDetailService;

    @Autowired
    private IMSalesDetailService salesDetailService;

    @Autowired
    private IMSalesService salesService;

    @Autowired
    private ICCheckService checkService;

    @Autowired
    private ICCheckDetailService checkDetailService;

    @Autowired
    private IWWearhouseService wearhouseService;

    @Autowired
    private IGoodsPartService goodsPartService;

    @Autowired
    private IBybsService bybsService;

    @Autowired
    private IBybsDetailService bybsDetailService;

    @Autowired
    private ISysDictService sysDictService;

    @Autowired
    private OutRepositoryDetailMapper outRepositoryDetailMapper;
    @Autowired
    private IMSalesService imSalesService;
    @Autowired
    private IWRelativeUnitService relativeUnitService;
    @Autowired
    private GoodsOrderMapper goodsOrderMapper;
    @Autowired
    private ISysUserService sysUserService;
    @Autowired
    private IPurchaseReturnService purchaseReturnService;

    @PostMapping
    @ResponseBody
    public MyResponseBody post(OutRepositoryDetail outRepositoryDetail) {
        outRepositoryDetailService.insertOrUpdate(outRepositoryDetail);
        return MyResponseBody.success();
    }

    @PostMapping("delete")
    @ResponseBody
    public MyResponseBody delete(@RequestParam("ids[]") List<Long> ids) {
        MyResponseBody responseBody = MyResponseBody.success();
        outRepositoryDetailService.delete(ids);
        return responseBody;
    }

    @GetMapping("{id}")
    @ResponseBody
    public MyResponseBody get(@PathVariable("id") Long id) {
        MyResponseBody responseBody = MyResponseBody.success();
        responseBody.setData(outRepositoryDetailService.selectById(id));
        return responseBody;
    }

    @GetMapping("edit")
    public String edit(OutRepositoryDetail outRepositoryDetail, ModelMap modelMap) {
        modelMap.put("id", outRepositoryDetail.getId());
        return "/outRepositoryDetail/outRepositoryDetail_edit";
    }

    @GetMapping("list")
    @ResponseBody
    public Page list(OutRepositoryDetailSearchDto searchDto, MyPage<OutRepositoryDetail> page) {
        return outRepositoryDetailService.selectPage(searchDto, page);
    }

    @RequestMapping("getOne")
    @ResponseBody
    public List<Map> getOne(String code) {
        List<Map> maps = outRepositoryDetailService.getDetailByCode(code);
        for (Map dto : maps) {
            if ("0".equals(dto.get("type").toString())) {
                Wrapper wrapper = new EntityWrapper<>();
                wrapper.eq("id", dto.get("buszId"));
                MSalesDetail detail = salesDetailService.selectOne(wrapper);
                dto.put("price", detail.getPrice());
            }
            if ("6".equals(dto.get("type").toString())) {
                Wrapper wrapper = new EntityWrapper<>();
                wrapper.eq("id", dto.get("buszId"));
                PurchaseReturn purchaseReturn = purchaseReturnService.selectOne(wrapper);
                dto.put("price", purchaseReturn.getUnitPrice());
            }
        }
        List<Map> unit = sysDictService.selList(DictCodes.get("materiel_MU"));
        for (int i = 0;i < maps.size(); i++) {
            for (int j =0;j<unit.size();j++) {
                if (maps.get(i).get("unit") != null && maps.get(i).get("unit").toString().equals(unit.get(j).get("value"))) {
                    maps.get(i).put("unitName", unit.get(j).get("text"));
                }
            }
        }
        return maps;
    }

    @GetMapping
    public String index(Long houseId, ModelMap map) {
        if(houseId != null && houseId != 0) {
            map.put("houseId", houseId);
            WWearhouse house = this.wearhouseService.selectById(houseId);
            map.put("houseName", house.getName());

            //本月
            map.put("startTime", DateUtil.getMonthFirstDay(new Date()));
            map.put("endTime", DateUtil.DateToString(new Date(), DateStyle.YYYY_MM_DD));
        }
        return "/outRepositoryDetail/outRepositoryDetail";
    }

    @RequestMapping("addOutRepositoryOrder")
    public String addOutRepositoryOrder(){
        return "/outRepositoryDetail/outRepositoryAdd";
    }

    @PostMapping("add")
    @ResponseBody
    public MyResponseBody add(OutRepositoryDetailAddDTO dto, String goods) {
        MyResponseBody responseBody = MyResponseBody.success();
        List<InRepositoryGoodsDTO> goodsList = JSONArray.parseArray(goods, InRepositoryGoodsDTO.class);
        dto.setInRepositoryGoodsDTOs(goodsList);
        outRepositoryDetailService.addOutRepositoryDetail(dto);
        return responseBody;
    }

    @GetMapping("detail")
    public String detail(@RequestParam("code") String code, ModelMap modelMap) {
        modelMap.put("code", code);
        Wrapper wrapper = new EntityWrapper();
        wrapper.eq("code", code);

        OutRepositoryDetail detail = this.outRepositoryDetailService.selectOne(wrapper);
        modelMap.put("type", detail.getType());
        if(detail.getType() == 0) {//销售出库
            MSalesDetail salesDetail = this.salesDetailService.selectById(detail.getBuszId());
            if (salesDetail != null) {
                MSales sales = this.salesService.selectById(salesDetail.getSalesId());
                modelMap.put("ctime", DateUtil.DateToString(sales.getCtime(), DateStyle.YYYY_MM_DD_HH_MM_SS));
                modelMap.put("username", sales.getUsername());
                modelMap.put("orderTime", DateUtil.DateToString(sales.getOrderTime(), DateStyle.YYYY_MM_DD));
            } else {
                //为空时天天爱车平台发货出库
                modelMap.put("ctime", DateUtil.DateToString(detail.getCtime(), DateStyle.YYYY_MM_DD_HH_MM_SS));
                modelMap.put("username", detail.getUsername());
                modelMap.put("orderTime", DateUtil.DateToString(detail.getOrderTime(), DateStyle.YYYY_MM_DD));
            }
        } else if(detail.getType() == 1) {//盘点出库
            CCheckDetail checkDetail = this.checkDetailService.selectById(detail.getBuszId());
            CCheck check = this.checkService.selectById(checkDetail.getCheckId());
            modelMap.put("ctime", DateUtil.DateToString(check.getCtime(), DateStyle.YYYY_MM_DD_HH_MM_SS));
            modelMap.put("username", check.getUsername());
            modelMap.put("orderTime", DateUtil.DateToString(check.getCtime(), DateStyle.YYYY_MM_DD));
        } else if(detail.getType() == 2) {//拆装出库
            GoodsPart part = this.goodsPartService.selectById(detail.getBuszId());
            modelMap.put("ctime", DateUtil.DateToString(part.getCtime(), DateStyle.YYYY_MM_DD_HH_MM_SS));
            modelMap.put("username", part.getCname());
            modelMap.put("orderTime", DateUtil.DateToString(part.getOrderTime(), DateStyle.YYYY_MM_DD));
        }  else if(detail.getType() == 3) {//报损出库
            BybsDetail bybsDetail = this.bybsDetailService.selectById(detail.getBuszId());
            Bybs bybs = this.bybsService.selectById(bybsDetail.getBybsId());
            modelMap.put("ctime", DateUtil.DateToString(bybs.getCtime(), DateStyle.YYYY_MM_DD_HH_MM_SS));
            modelMap.put("username", bybs.getCname());
            modelMap.put("orderTime", DateUtil.DateToString(bybs.getOrderTime(), DateStyle.YYYY_MM_DD));
        }
        return "/outRepositoryDetail/outRepositoryDetail_new";
    }

    @GetMapping("printList")
    public String printList(@RequestParam("ids") Long[] ids, ModelMap modelMap) {
        modelMap.put("thisTime", DateUtil.DateToString(new Date(), DateStyle.YYYY_MM_DD_HH_MM_SS));
        String idsList = "(";
        for (int i = 0; i < ids.length; i++) {
            idsList += ids[i] + ",";
        }
        idsList = idsList.substring(0, idsList.length() - 1);
        idsList = idsList + ")";
        modelMap.put("ids",idsList);
        return "/outRepositoryDetail/outRepositoryList_print";
    }

    @RequestMapping("printData")
    @ResponseBody
    public List printData(@RequestParam("ids") String ids){
        Map map = new HashMap<>(2);
        map.put("ids", ids);
        List<Map> maps = outRepositoryDetailMapper.selectPrintList(map);
        List<Map> repository = sysDictService.selList(DictCodes.get("outRepository"));
        for (int i = 0;i < maps.size(); i++) {
            maps.get(i).put("orderTime",DateUtil.DateToString((Date) maps.get(i).get("orderTime"), DateStyle.YYYY_MM_DD));
            if ("0".equals(String.valueOf( maps.get(i).get("type")))) {
                Wrapper wrapper = new EntityWrapper<>();
                wrapper.eq("id",maps.get(i).get("busz_id"));
                MSales mSales = imSalesService.selectOne(wrapper);
                Wrapper w = new EntityWrapper<>();
                if (mSales != null) {
                    w.eq("id", mSales.getCusId());
                    WRelativeUnit wRelativeUnit = relativeUnitService.selectOne(w);
                    maps.get(i).put("customName", wRelativeUnit.getName());
                }
            }
            if ("4".equals(String.valueOf(maps.get(i).get("type")))) {
                String goodsId = String.valueOf(maps.get(i).get("busz_id"));
                String customName = goodsOrderMapper.queryCustomName(goodsId);
                maps.get(i).put("customName", customName);
            }
            for (int j =0;j<repository.size();j++) {
                if (maps.get(i).get("type").toString().equals(repository.get(j).get("value"))) {
                    maps.get(i).put("typeName", repository.get(j).get("text"));
                }
            }
        }
        return maps;
    }

    @GetMapping("printDetail")
    public String printDetail(@RequestParam("code") String code, ModelMap modelMap) {
        modelMap.put("thisTime", DateUtil.DateToString(new Date(), DateStyle.YYYY_MM_DD_HH_MM_SS));
        modelMap.put("code", code);
        String id = "(" + code +")";
        Map map = new HashMap<>();
        map.put("ids", id);
        List<Map> maps = outRepositoryDetailMapper.selectPrintList(map);
        modelMap.put("customName", maps.get(0).get("customName"));
        Wrapper wrapper2 = new EntityWrapper<>();
        wrapper2.eq("code", maps.get(0).get("code"));
        List<OutRepositoryDetail> outRepositoryDetails = outRepositoryDetailService.selectList(wrapper2);
        List idList = new ArrayList<>();
        for (OutRepositoryDetail dto : outRepositoryDetails) {
            idList.add(dto.getWearhouseId());
        }
        String repositoryName = "";
        Wrapper wrapper1 = new EntityWrapper<>();
        wrapper1.in("id", idList);
        List<WWearhouse> wWearhouses = wearhouseService.selectList(wrapper1);
        for (WWearhouse nameDto : wWearhouses) {
            repositoryName += nameDto.getName() + "，";
        }
        repositoryName = repositoryName.substring(0,repositoryName.length() - 1);
        modelMap.put("repositoryName", repositoryName);

        Wrapper wrapper = new EntityWrapper<>();
        wrapper.eq("username", maps.get(0).get("username"));
        SysUser sysUser = sysUserService.selectOne(wrapper);
        if (sysUser!= null && sysUser.getNickname() != null) {
            modelMap.put("nickname", sysUser.getNickname());
        } else {
            modelMap.put("nickname", maps.get(0).get("username"));
        }

        if ("0".equals(String.valueOf( maps.get(0).get("type")))) {
            Wrapper wrapper4 = new EntityWrapper<>();
            wrapper4.eq("id",maps.get(0).get("busz_id"));
            MSalesDetail detail = salesDetailService.selectOne(wrapper4);
            Wrapper w5 = new EntityWrapper<>();
            w5.eq("id", detail.getSalesId());
            MSales mSales = imSalesService.selectOne(w5);
            Wrapper w = new EntityWrapper<>();
            if (mSales != null) {
                w.eq("id", mSales.getCusId());
                WRelativeUnit wRelativeUnit = relativeUnitService.selectOne(w);
                modelMap.put("customName", wRelativeUnit.getName());
            }
        }
        if ("4".equals(String.valueOf(maps.get(0).get("type")))) {
            String goodsId = String.valueOf(maps.get(0).get("busz_id"));
            String customName = goodsOrderMapper.queryCustomName(goodsId);
            modelMap.put("customName", customName);
            maps.get(0).put("rcode", goodsId);
        }
        modelMap.put("data", maps.get(0));

        List<Map> repository = sysDictService.selList(DictCodes.get("outRepository"));
        maps.get(0).put("orderTime",DateUtil.DateToString((Date) maps.get(0).get("orderTime"), DateStyle.YYYY_MM_DD));
        for (int j = 0; j < repository.size(); j++) {
            if (maps.get(0).get("type").toString().equals(repository.get(j).get("value"))) {
                maps.get(0).put("typeName", repository.get(j).get("text"));
            }
        }

        List<Map> goodsMap = outRepositoryDetailService.getDetailByCode((String) maps.get(0).get("code"));
        for (Map dto : goodsMap) {
            if ("0".equals(dto.get("type").toString())) {
                Wrapper wrapper3 = new EntityWrapper<>();
                wrapper3.eq("id", dto.get("buszId"));
                MSalesDetail detail = salesDetailService.selectOne(wrapper3);
                dto.put("price", detail.getPrice());
            }
            if ("6".equals(dto.get("type").toString())) {
                Wrapper wrapper4 = new EntityWrapper<>();
                wrapper4.eq("id", dto.get("buszId"));
                PurchaseReturn purchaseReturn = purchaseReturnService.selectOne(wrapper4);
                dto.put("price", purchaseReturn.getUnitPrice());
            }
        }
        Integer totalCount = 0;
        BigDecimal totalMoney = BigDecimal.ZERO;
        if (goodsMap != null && goodsMap.size() > 0) {
            for (int i = 0; i< goodsMap.size(); i++) {
                totalCount += (Integer) goodsMap.get(i).get("count");
                if (goodsMap.get(i).get("price") != null) {
                    BigDecimal count = new BigDecimal((Integer) goodsMap.get(i).get("count")) ;
                    BigDecimal price =  (BigDecimal) goodsMap.get(i).get("price") ;
                    BigDecimal multiply = count.multiply(price).setScale(2);
                    totalMoney = totalMoney.add(multiply);
                }
            }
        }
        modelMap.put("totalCount", totalCount);
        modelMap.put("totalMoney", totalMoney.toString());
        String capitalMoney = "零元整";
        if(BigDecimal.ZERO.compareTo(totalMoney)!=0){
            capitalMoney = MoneyTransformUtil.digitUppercase(totalMoney.toString());
        }
        modelMap.put("capitalMoney", capitalMoney);
        return "/outRepositoryDetail/outPrintDetail";
    }

}
